package net.adst.ui.other;

import net.adst.beans.User;
import net.adst.resources.Constants;
import net.adst.util.GBC;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.*;
import sun.net.ResourceManager;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 04.12.12
 * Time: 2:20
 * To change this template use File | Settings | File Templates.
 */
public class EditUsersDialog extends JDialog {

    private JLabel loginLabel;
    private JTextField loginField;

    private JLabel passwordLabel;
    private JTextField passwordField;

    private JLabel roleLabel;
    private JComboBox roleCombo;

    private JTable usersTable;
    private DefaultTableModel tableModel;

    private JButton saveButton;
    private JButton clearButton;
    private JButton removeButton;

    HSSFWorkbook wb;
    private User user;

    public EditUsersDialog(User user) {
        setLayout(new GridBagLayout());
        this.user = user;
        addElements();

    }

    private void addElements() {
        Dimension dim = new Dimension(110, 17);
        loginLabel = new JLabel("логин:");
        loginLabel.setMinimumSize(dim);
        loginLabel.setMaximumSize(dim);
        loginLabel.setPreferredSize(dim);
        loginField = new JTextField();
        loginField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                saveButton.setEnabled(true);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                if (loginField.getText().isEmpty())
                    saveButton.setEnabled(false);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
            }
        });

        passwordLabel = new JLabel("пароль:");
        passwordLabel.setMinimumSize(dim);
        passwordLabel.setMaximumSize(dim);
        passwordLabel.setPreferredSize(dim);
        passwordField = new JTextField();
        roleLabel = new JLabel("роль в программе:");
        roleLabel.setMinimumSize(dim);
        roleLabel.setMaximumSize(dim);
        roleLabel.setPreferredSize(dim);
        roleCombo = new JComboBox();
        DefaultComboBoxModel roleModel = new DefaultComboBoxModel();
        roleModel.addElement("Администратор");
        roleModel.addElement("Менагер");
        roleCombo.setModel(roleModel);
        tableModel = new DefaultTableModel( //NotEditableDefaultTableModel
                new Object[][]{
                },
                Constants.USERS_НEADER
        ) {
            @Override
            public boolean isCellEditable(final int row, final int col) {
                return false;
            }
        };
        usersTable = new JTable(tableModel);
        usersTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        usersTable.setRowHeight(Constants.TABLE_ROW_HEIGHT);
        usersTable.getTableHeader().setReorderingAllowed(false);
        usersTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting())
                    return;
                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                if (!lsm.isSelectionEmpty()) {
                    saveButton.setEnabled(true);
                    final int selectedRow = lsm.getMinSelectionIndex();
                    if (selectedRow > -1) {
                        removeButton.setVisible(true);
                        loginField.setText(usersTable.getValueAt(selectedRow, 0).toString());
                        if (user.getLogin().equalsIgnoreCase(usersTable.getValueAt(selectedRow, 0).toString())) {
                            passwordField.setText(user.getPassword());
                            passwordField.setForeground(Color.BLACK);
                        } else {
                            passwordField.setText("нельзя менять пароль");
                            passwordField.setForeground(Color.GRAY);
                        }
                        roleCombo.setSelectedIndex(1);
                        for (int k = 0; k < Constants.adm.length; k++) {
                            if (usersTable.getValueAt(selectedRow, 2).toString().equalsIgnoreCase(Constants.adm[k])) {
                                roleCombo.setSelectedIndex(0);
                            }
                        }
                    }
                }
            }
        }

        );
        saveButton = new JButton("Сохранить");

        saveButton.setFocusPainted(false);
        saveButton.setEnabled(false);
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    ExcelExtractor extractor = new ExcelExtractor(wb);
                    extractor.setFormulasNotResults(false); // Считать формулы
                    HSSFSheet sheet = wb.getSheet("люди");
                    if (usersTable.getSelectedRow() > -1) {
                        if (user.getLogin().equals(usersTable.getValueAt(usersTable.getSelectedRow(), 0).toString())) {
                            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                                if (sheet.getRow(i) != null) {
                                    if (sheet.getRow(i).getCell(1).toString().equalsIgnoreCase(usersTable.getValueAt(usersTable.getSelectedRow(), 0).toString())) {
                                        sheet.getRow(i).getCell(1).setCellValue(loginField.getText());
                                        sheet.getRow(i).getCell(2).setCellValue(passwordField.getText().toString().hashCode());
                                        sheet.getRow(i).getCell(3).setCellValue(roleCombo.getSelectedItem().toString());
                                        break;
                                    }
                                }
                            }

                        } else {
                            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                                if (sheet.getRow(i) != null) {
                                    if (sheet.getRow(i).getCell(1).toString().equalsIgnoreCase(usersTable.getValueAt(usersTable.getSelectedRow(), 0).toString())) {
                                        sheet.getRow(i).getCell(1).setCellValue(loginField.getText());
                                        sheet.getRow(i).getCell(3).setCellValue(roleCombo.getSelectedItem().toString());
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                        HSSFCellStyle style = sheet.getRow(sheet.getLastRowNum() - 1).getCell(1).getCellStyle();
                        HSSFCell cel1 = row.createCell(1);
                        cel1.setCellValue(loginField.getText());
                        cel1.setCellStyle(style);
                        HSSFCell cel2 = row.createCell(2);
                        cel2.setCellValue(passwordField.getText().toString().hashCode());
                        cel2.setCellStyle(style);
                        HSSFCell cel3 = row.createCell(3);
                        cel3.setCellValue(roleCombo.getSelectedItem().toString());
                        cel3.setCellStyle(style);

                    }
                    FileOutputStream fileOut = new FileOutputStream("d:\\adst\\adst\\src\\main\\resources\\info.xls");
                    wb.write(fileOut);
                    fileOut.close();
                    JOptionPane.showMessageDialog(null, "Изменение успешно сохранены", "Изменения сохранены", JOptionPane.OK_OPTION, new ImageIcon(ResourceManager.class.getResource("/images/success.png")));
                } catch (IOException e1) {
                    JOptionPane.showOptionDialog(null, "Нет доступа к базе данных. Проверьте соединени с сервером", "парольбыл не изменен", JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE, null, null, null);
                }
            }
        });
        clearButton = new JButton("Очистить форму");
        clearButton.setFocusPainted(false);
        clearButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loginField.setText("");
                passwordField.setText("");
                usersTable.getSelectionModel().clearSelection();
                roleCombo.setSelectedIndex(1);
                saveButton.setEnabled(false);
                passwordField.setForeground(Color.BLACK);
                removeButton.setVisible(false);
            }
        });

        removeButton = new JButton("удалить пользователя");
        removeButton.setFocusPainted(false);
        removeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    InputStream in = EditUsersDialog.class.getClassLoader().getSystemResourceAsStream("info.xls");
                    HSSFWorkbook wb = null;
                    wb = new HSSFWorkbook(in);
                    ExcelExtractor extractor = new ExcelExtractor(wb);
                    extractor.setFormulasNotResults(false); // Считать формулы
                    HSSFSheet sheet = wb.getSheet("люди");
                    if (usersTable.getSelectedRow() > -1) {
                        if (user.getLogin().equals(usersTable.getValueAt(usersTable.getSelectedRow(), 0).toString())) {
                            JOptionPane.showMessageDialog(null, "Удалять себя это плохая идея", "Ошибка", JOptionPane.ERROR_MESSAGE);
                        } else {
                            int response = JOptionPane.showOptionDialog(null, "Вы уверены что хотите удалить " + usersTable.getValueAt(usersTable.getSelectedRow(), 0).toString(), "Удалить пользователя?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, null, null);
                            if (response == JOptionPane.NO_OPTION) {
                                //                            rc = fileChooser.showSaveDialog(null);
                            }
                            if (response == JOptionPane.YES_OPTION) {
                                for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                                    if (sheet.getRow(i) != null) {
                                        if (sheet.getRow(i).getCell(1).toString().equalsIgnoreCase(usersTable.getValueAt(usersTable.getSelectedRow(), 0).toString())) {
                                            sheet.removeRow(sheet.getRow(i));
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                    }

                } catch (IOException e1) {
                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
        JScrollPane scrollPane = new JScrollPane(usersTable);

        add(loginLabel, new GBC(0, 0).setInsets(3, 5, 0, 0).setAnchor(GBC.WEST));
        add(loginField, new GBC(0, 1).setInsets(1, 5, 0, 0).setFill(GBC.HORIZONTAL).setAnchor(GBC.WEST));
        add(passwordLabel, new GBC(1, 0).setInsets(3, 5, 0, 0).setAnchor(GBC.WEST));
        add(passwordField, new GBC(1, 1).setInsets(1, 5, 0, 0).setFill(GBC.HORIZONTAL).setAnchor(GBC.WEST));
        add(roleLabel, new GBC(2, 0).setInsets(3, 5, 0, 0).setAnchor(GBC.WEST));
        add(roleCombo, new GBC(2, 1).setInsets(1, 5, 0, 0).setFill(GBC.HORIZONTAL).setAnchor(GBC.WEST));
        add(saveButton, new GBC(3, 1).setInsets(3, 5, 0, 0).setAnchor(GBC.CENTER));
        add(removeButton, new GBC(2, 2).setInsets(3, 5, 0, 0).setAnchor(GBC.CENTER));
        add(clearButton, new GBC(3, 2).setInsets(3, 5, 0, 0).setAnchor(GBC.CENTER));
        add(scrollPane, new GBC(0, 3, 4, 1).setFill(GBC.BOTH).setWeight(1, 1));
    }

    public void init() {
        setDialogSettings();
        fillingTable();
        getContentPane().setBackground(Constants.COLOR_LIGHT_BLUE);
        removeButton.setVisible(false);
        setVisible(true);


    }

    private void fillingTable() {
        try {
            InputStream in = EditUsersDialog.class.getClassLoader().getSystemResourceAsStream("info.xls");
            HSSFWorkbook wb = null;
            wb = new HSSFWorkbook(in);
            ExcelExtractor extractor = new ExcelExtractor(wb);
            extractor.setFormulasNotResults(false); // Считать формулы
            HSSFSheet sheet = wb.getSheet("люди");
            for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
                if (sheet.getRow(i) != null) {
                    this.tableModel.addRow(new Object[]{sheet.getRow(i).getCell(1) != null ? sheet.getRow(i).getCell(1).toString() : "", sheet.getRow(i).getCell(2) != null ? "XXXXXXXXX" : "", sheet.getRow(i).getCell(3) != null ? sheet.getRow(i).getCell(3).toString() : ""});
                }
            }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    private void setDialogSettings() {
        setModal(true);
        setResizable(false);
        setModalityType(ModalityType.APPLICATION_MODAL);
        pack();
        setLocationRelativeTo(Frame.getFrames()[0]);
        setTitle("Работа с кадрами.");
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        getRootPane().setDefaultButton(saveButton);
    }


}
